package com.itboye.ihomebank.zjtlcb.lnd.livenessdetector.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;

import com.itboye.ihomebank.activity.qianyue.OrderDetailActivity;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.oliveapp.liveness.sample.liveness.view_controller.LivenessDetectionMainActivity;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.zjtlcb.lnd.livenessdetector.utils.OkHttpRequestUtil;
import com.itboye.ihomebank.zjtlcb.lnd.livenessdetector.utils.security.SecurityUtil;
import com.oliveapp.face.livenessdetectorsdk.livenessdetector.datatype.LivenessDetectionFrames;
import com.oliveapp.face.livenessdetectorsdk.livenessdetector.datatype.LivenessSessionState;
import com.oliveapp.face.livenessdetectorsdk.livenessdetector.datatype.OliveappFaceInfo;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

public class DetecActionActivity extends LivenessDetectionMainActivity {
    public static final String TAG = DetecActionActivity.class.getSimpleName();
    private ProgressDialog mProgressDialog;
    private byte[] mPackageByteArray;
    private MyApplcation mApplication;
    private String requestCode3 = "";//请求标志
    private JSONObject mResponseResult;//获取金融云返回的json


    /**
     *发送判断活体检测与人脸是被是否为同一人的请求报文
     **/
    private String requestURL;
    private String appSecretKey;
    private String requestIsSamePersonJSon;//组装报文
    private String isSamePersonJSon;//加密后的组装报文

    private String appID = "";//APP秘钥
    private String seqNO = "";
    private String signMethod = "";
    private String encryptMethod = "";
    private String appAccessToken = "";
    private String sign = "";
    //head
    private String bussSeqNo = "";
    private String mrchSno = "";
    private String productId = "";
    private String txSno = "";
    private String txTime = "";
    //body
    private String sceneType;//识别场景
    private String checkImageContent ="";//检测照片包内容,即捕捉到的四张照片，做base64处理
    private String mAppAccessToken;
    private SharedPreferences mASp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mApplication = (MyApplcation)getApplication();
        mASp = getSharedPreferences("mainActivity", Context.MODE_PRIVATE);
        mAppAccessToken = mASp.getString("appAccessToken", "");
        appAccessToken = mAppAccessToken;
//        setContentView(R.layout.activity_detec_action);
    }

    /**=====================开始启动活体检测算法===============**/
    @Override
    public void onInitializeSucc() {
        super.onInitializeSucc();
        super.startVerification();
    }

    @Override
    public void onInitializeFail(Throwable e) {
        super.onInitializeFail(e);
        Log.e(TAG, "无法初始化活体检测,请检测是否已打开APP相机权限");
        Toast.makeText(this, "无法初始化活体检测,请确认是否已打开APP相机权限", Toast.LENGTH_LONG).show();

        finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if ((mProgressDialog != null) && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    /**===================================活体检测算法调用==================================**/
    @Override
    public void onLivenessSuccess(OliveappFaceInfo oliveappFaceInfo) {
        Log.e(TAG,"捕获到的人脸信息：左眼:"+oliveappFaceInfo.leftEye+",右眼:"+oliveappFaceInfo.rightEye
        +",嘴巴："+oliveappFaceInfo.mouthCenter+",正面："+oliveappFaceInfo.chin);

        super.onLivenessSuccess(null, oliveappFaceInfo);
        CheckImagePackage checkImagePackage = new CheckImagePackage();
        checkImagePackage.execute();
    }

    /**
     * 获取大礼包并访问TLCB金融云平台
     */
    private class CheckImagePackage extends AsyncTask<Void, Void, JSONObject> {
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(DetecActionActivity.this,null, "正在比对，请稍等", true, false);
        }

        @Override
        protected JSONObject doInBackground(Void... voids) {
            // 获取大礼包，耗时操作，不可在UI线程执行
            LivenessDetectionFrames pkg = getLivenessDetectionPackage();
            Log.e(TAG, "大礼包信息："+pkg);
            if (pkg == null) {
                return null;
            }
            mPackageByteArray = pkg.verificationData;

            //调用金融云连接的协同作业平台的人脸识别接口,判断是否为同一人
            MyApplcation requestBean = new MyApplcation();
            appSecretKey = requestBean.appSecretKey;
            requestCode3 = requestBean.requestCode3;
            requestURL = requestBean.requestURL;

            appID = requestBean.appID;
            seqNO = requestBean.seqNO;
            signMethod = requestBean.signMethod;
            encryptMethod = requestBean.encryptMethod;

            SharedPreferences mASp = getSharedPreferences("mainActivity", Context.MODE_PRIVATE);
            String mAppAccessToken = mASp.getString("appAccessToken", "");
            appAccessToken = mAppAccessToken;
            sign = requestBean.sign;
            //head
            txSno = requestBean.txSno;
            mrchSno = requestBean.mrchSno;
            bussSeqNo = mApplication.getBussSeqNo();
            txTime = requestBean.txTime;
            productId = requestBean.productId;
            //body
            sceneType = requestBean.sceneType;
            checkImageContent = Base64.encodeToString(mPackageByteArray, Base64.NO_WRAP);
            Log.e(TAG, "大礼包中图片：" + checkImageContent);

            requestIsSamePersonJSon =        //发送人脸识别交易报文
                    "{" +
                            "\"appID\": "+"\""+appID+"\"," +
                            "\"seqNO\":"+"\""+seqNO+"\"," +
                            "\"signMethod\":"+"\""+signMethod+"\"," +
                            "\"encryptMethod\":"+"\""+encryptMethod+"\"," +
                            "\"appAccessToken\":"+"\""+appAccessToken+"\"," +
                            "\"sign\":"+"\""+sign + "\"," +
                            "\"reqData\":{" +
                                "\"body\":{"+
                                    "\"sceneType\":"+"\""+ sceneType +"\"," +
                                    "\"checkImageContent\":"+"\""+checkImageContent +"\"" +
                                    "},"+
                                "\"head\":{"+
                                    "\"txSno\":"+"\""+txSno+"\"," +
                                    "\"mrchSno\":"+"\""+mrchSno+"\"," +
                                    "\"bussSeqNo\":"+"\""+bussSeqNo+"\"," +
                                    "\"txTime\":"+"\""+txTime+"\"," +
                                    "\"productId\":"+"\""+productId+"\"" +
                                    "}"+
                            "}"+
                    "}";
            Log.e(TAG, "发送判断活体检测与人脸是被是否为同一人的请求报文："+requestIsSamePersonJSon);

            //加密处理
            SecurityUtil.setSecretKey(appSecretKey);
            isSamePersonJSon = SecurityUtil.toJson(requestIsSamePersonJSon);

            OkHttpRequestUtil OHRUtil = new OkHttpRequestUtil();
            Log.e(TAG, requestCode3+ "加密后发送的报文：" + isSamePersonJSon);
            String isSamePersonResponse = null;
            try {
                isSamePersonResponse = OHRUtil.okHttpRequest(isSamePersonJSon, requestURL, requestCode3,TAG);
                Log.e(TAG, requestCode3+"获取金融云返回："+isSamePersonResponse);
                mResponseResult = new JSONObject(isSamePersonResponse);
            }catch (JSONException e) {
                e.printStackTrace();
            }catch (IOException e) {
                e.printStackTrace();
            }

            Log.e(TAG, "doInBackground: 返回的结果"+mResponseResult);
            return mResponseResult;
        }

        @Override
        protected void onPostExecute(JSONObject result) {
            String errorCode = result.optString("errorCode");//解析到金融云返回errorCode
            Log.e(TAG, requestCode3 + "接收到金融云返回结果为：" + result+",errorCode："+ errorCode);

            if(errorCode.equals("000000")){
                mApplication.setIsSamePerson("true");
                //成功
                if (OrderDetailActivity.url!=null){
                    Uri uri = Uri.parse(OrderDetailActivity.url);
                    Intent intent4 = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent4);
                }
//                setResult(OrderDetailActivity.TAILONGREQUEST);
            }else{
                mApplication.setIsSamePerson("false");
                ByAlert.alert(result.optString("errorMsg"));
            }
            finish();
        }
    }
    /**
     * 活检阶段失败
     */
    @Override
    public void onLivenessFail(int result, LivenessDetectionFrames livenessDetectionFrames) {
        super.onLivenessFail(result, livenessDetectionFrames);

        final int code = result;
        Handler handler = new Handler();
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (code == LivenessSessionState.SESSION_TIMEOUT) {//超时
                    Toast.makeText(DetecActionActivity.this, "网络超时", Toast.LENGTH_SHORT).show();
                } else {//活检失败
                    Toast.makeText(DetecActionActivity.this, "活检失败", Toast.LENGTH_SHORT).show();
                }
                finish();
            }
        });
    }
}
